package com.jackrain.nea.clould.dao;

import com.alibaba.fastjson.JSONArray;
import com.jackrain.nea.clould.model.TopicModel;
import com.jackrain.nea.util.Tools;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.Date;

/**
 * 查询Topic
 */
@Slf4j
@Component
public class TopicDao {

    /**
     * 查询topicID和clientID
     *
     * @param topic
     * @return
     * @throws Exception
     */
    public JSONArray queryTopic(String topic) throws Exception {

        String sql = "select id,ad_client_id " +
                " from oms_topic" +
                " where TOPIC = ?";

        JSONArray retArray = QueryEngine.getInstance().doQueryObjectArray(sql, new Object[]{topic});

        return retArray;
    }

    public int queryTopicID(String topic) throws Exception {

        String sql = "select id " +
                " from oms_topic" +
                " where TOPIC = ?";

        int ret = Tools.getInt(QueryEngine.getInstance().doQueryOne(sql, new Object[]{topic}), 0);

        return ret;
    }

    /**
     * 通过商户ID查询topic
     *
     * @param clientID
     * @return
     * @throws Exception
     */
    public JSONArray queryTopic(int clientID) throws Exception {

        String sql = "select id,topic,topicname " +
                " from oms_topic" +
                " where ad_client_id = ?";

        JSONArray retArray = QueryEngine.getInstance().doQueryObjectArray(sql, new Object[]{clientID});

        return retArray;
    }

    /**
     * 查询所有的topic
     *
     * @return
     * @throws Exception
     */
    public JSONArray queryTopic() throws Exception {

        String sql = "select id,topic,topicname,ad_client_id " +
                " from oms_topic";

        JSONArray retArray = QueryEngine.getInstance().doQueryObjectArray(sql);

        return retArray;
    }

    public int save(TopicModel topicModel) {

        String sql = "insert into oms_topic " +
                "(id,ad_client_id, topic,topicname" +
                ",ownerid,modifierid,creationdate,modifieddate,isactive)" +
                "values(?,?,?,?" +
                ",?,?,?,?,?) " +
                "ON DUPLICATE KEY UPDATE modifieddate = ?";

        Timestamp time = new Timestamp(new Date().getTime());

        int ret = QueryEngine.getInstance().executeUpdate(sql, new Object[]{com.jackrain.nea.core.db.Tools.getSequence("oms_topic"),
                topicModel.getAd_client_id(), topicModel.getTopic(), topicModel.getTopicname(), 893, 893, time, time, "Y", time});


        return ret;

    }


}
